<template>
<div>
  <!-- #ifndef MP-WEIXIN -->
  <view class="purple_btn btn_box" @click="saveImgToLocal">
    保存到相册
  </view>
  <!-- #endif -->

  <!-- #ifdef MP-WEIXIN -->
  <view v-if="openSettingBtnHidden" class="purple_btn btn_box" @click="saveEwm">
    保存到相册
  </view>

  <button v-else class="purple_btn btn_box" hover-class="none" open-type="openSetting" @opensetting='handleSetting'>保存到相册</button>
  <!-- #endif -->



</div>
</template>

<script>
var _self;
export default{
  data(){
    return {
      openSettingBtnHidden: true,//是否授权
      ewmImg:""//这是要保存的图片
    }
  },
  onLoad(opt) {
    _self = this;
  },
  components:{
  },
  methods:{
    //微信小程序保存到相册
    handleSetting(e){
      if (!e.detail.authSetting['scope.writePhotosAlbum']) {
        _self.openSettingBtnHidden = false;
      } else {
        _self.openSettingBtnHidden = true;
      }
    },
    saveEwm:function(e){
      //获取相册授权
      uni.getSetting({
        success(res) {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            uni.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {
                //这里是用户同意授权后的回调
                _self.saveImgToLocal();
              },
              fail() {//这里是用户拒绝授权后的回调
                _self.openSettingBtnHidden=false
              }
            })
          } else {//用户已经授权过了
            _self.saveImgToLocal();
          }
        }
      })
    },
    saveImgToLocal:function(e){

      uni.showModal({
        title: '提示',
        content: '确定保存到相册吗',
        success: function (res) {
          if (res.confirm) {

            uni.downloadFile({
              url: _self.ewmImg,//图片地址
              success: (res) =>{
                if (res.statusCode === 200){
                  uni.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: function() {
                      uni.showToast({
                        title: "保存成功",
                        icon: "none"
                      });
                    },
                    fail: function() {
                      uni.showToast({
                        title: "保存失败",
                        icon: "none"
                      });
                    }
                  });
                }
              }
            })


          } else if (res.cancel) {

          }
        }
      });

    }
  }
}

</script>

<style scoped>

</style>